<template>
	<view class="page">
		<!--    <image class="log" src="/static/img/help.png" mode="widthFix" @click="toggleLog"></image>-->
		<view class="nav-style" :style="{'height':navHeight+'px'}">
			<image class="back-img" src="/static/img/back.png" mode="aspectFit" :style="{'top':statusBarHeight+'px'}"
				@click="back"></image>
			<image class="small-logo" src="/static/img/logo-white.png" mode="aspectFit"
				:style="{'padding-top':statusBarHeight+'px'}"></image>
		</view>
		<view v-if="[4, 5].includes(info.step)" class="process-wrap" :style="{'padding-top': (navHeight + 20) +'px'}">
			<!-- <process :active="info.step" :steps="collectionStepsData" /> -->
		</view>
		<!--    <image class="header" src="/static/image/header.png" mode="aspectHeightFit" />-->
		<view class="wrap" :style="{'margin-top': [1, 2, 3, 6, 7].includes(info.step) ? navHeight + 'px' : '0' }">
			<test-check ref="testCheck" :info="info" :time="times" :device-number="deviceNumber" @back="back"
				@next="onConfirm" />
		</view>
		<uni-popup ref="popup" :mask-click="false" :is-mask-click="false" type="center">
			<view class="popup-wrap">
				<image class="popup-bg" src="/static/img/tips-bg.png" mode="aspectFit" />
				<view class="popup-container">
					<view class="popup-title">
						<image class="popup-img" src="/static/img/tips-icon.png" mode="aspectFit" />
						<view class="popup-text">温馨提示</view>
					</view>
					<view class="popup-content">疾控中心将在保障您隐私的前提下，提供进一步检测、知识咨询、预防措施等服务，请问您是否需要？</view>
					<view class="popup-btn-wrap">
						<view class="popup-btn cancel" @click="onCancel">不需要</view>
						<view class="popup-btn need" @click="onNeed">需要（推荐）</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="log" :mask-click="false" :is-mask-click="false" type="center">
			<div class="logs">
				<button class="log-close" @click="closeLog">关闭</button>
				<div v-for="item in logs" :key="item.time" class="log-item">{{ item.value }}</div>
			</div>
		</uni-popup>
	</view>
</template>

<script>
	// import permision from "@/js_sdk/wa-permission/permission.js"
	// import { checkOpenGPSServiceByAndroid } from "@/utils/device";
	import TestCheck from '@/pages/home/components/test-check/index.vue'
	import Process from '../../components/process/index.vue'
	import {
		ab2hex,
		sleep,
		stringToHex,
		debounce
	} from '@/utils/util.js'
	import {
		UDI,
		AESEncrypt,
		AESDecrypt,
		CreateReagentResult,
		UpdateReagentResult,
		ConvertCoordinate,
		GetReleted,
		CreateReleted,
		aesDecryptjieguozhi,
		UpReagentResult,
		aesDecrypt2,
		aesDecryptGetAPiyuzhi
	} from '@/utils/api.js'
	const platform = uni.getSystemInfoSync().platform
	const baseSecret = '4B65487561BFC6'
	// const HANDLE_0x1800 = '00001800-0000-1000-8000-00805f9b34fb'
	// const HANDLE_0x2A00 = '00002A00-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9000 = '00009000-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9001 = '00009001-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9002 = '00009002-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9003 = '00009003-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9004 = '00009004-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9005 = '00009005-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9006 = '00009006-0000-1000-8000-00805F9B34FB'
	const HANDLE_0x9007 = '00009007-0000-1000-8000-00805F9B34FB'
	// let that = null
	let that
	export default {
		name: 'Home',
		components: {
			TestCheck,
			Process
		},
		data() {
			return {
				xitong:'',
				Reagentno:'',
				gps: false,
				result: 0,
				saveBluetoothDevice_key: "saveBluetoothDevice", //保存到本地存储中的key
				logs: [],
				isBack: false,
				valueChangeTimes: 0,
				locationTimer: 0,
				// isStartScan: false,
				bleAdapter: {
					available: false
				},
				bleConnection: false,
				processIndex: 1,
				isStartDiscovery: false,
				timer: null,
				resultTimer: null,
				navHeight: '',
				statusBarHeight: '',
				DetectionType: '',
				times: 0,
				step: 1,
				info: {
					step: 0,
					imageNum: '',
					name: '',
					image: '',
					custom: true,
					imageDesc: '',
					operateName: '',
				},
				blueDeviceList: [],
				blueDeviceList_1:[],
				process: [],
				deviceNumber: '',
				scanDeviceName: '',
				scanMac: '',
				// deviceName: '',
				deviceId: '',
				serviceId: '',
				characteristicId: '',
				key: '',
				iv: '',
				// readStepsData: [
				//   {
				//     step: 1,
				//     name: '材料检查'
				//   },
				//   {
				//     step: 2,
				//     name: '操作准备'
				//   },
				//   {
				//     step: 3,
				//     name: '开启设备'
				//   },
				//   {
				//     step: 4,
				//     name: '扫码连接'
				//   }
				// ],
				collectionStepsData: [{
						step: 2,
						name: '采血'
					},
					{
						step: 3,
						name: '检测'
					}
				],
				stepData: [{
						step: 1,
						steps: [{
								step: 1,
								imageNum: 1,
								name: '材料检查',
								// image: 'step-check.png',
								image: 'step-check-2.jpg',
								// content: ['请检查电子检测盒、采血针、滴管、酒精棉片、缓冲液等物品是否准备齐全。'],
								content: ['请检查阅读仪、采血针、滴管、酒精棉片、缓冲液等物品是否准备齐全。'],
							},
							{
								step: 2,
								imageNum: 2,
								name: '操作准备',
								image: 'step-operate.png',
								// content: ['1、洗手并消毒，在做测试前，手需要完全擦干；', '2、将电子检测盒取出，放在室温中；', '3、确认电子检测盒的效期在可使用范围内；',
								// 	'4、在撕口处打开铝箔袋，取出电子检测盒，滴液口向上，平放于桌面。'
								// ],
								content: ['1、洗手并消毒，在做测试前，手需要完全擦干；', '2、将阅读仪取出，放在室温中；', '3、确认阅读仪的效期在可使用范围内；',
									'4、在撕口处打开铝箔袋，取出阅读仪，滴液口向上，平放于桌面。'
								]
							},
							{
								step: 3,
								imageNum: 3,
								name: '开启设备',
								image: 'step-turn-on.png',
								// content: ['1、请拔出电池阻断塑料片；', '2、将电子检测盒放在距离手机50cm以内；', '3、观看电子检测盒指示灯是否闪烁。'],
								content: ['1、请拔出电池阻断塑料片；', '2、将阅读仪放在距离手机50cm以内；', '3、观看阅读仪指示灯是否闪烁。'],
							},
							{
								step: 4,
								imageNum: 4,
								name: '扫码连接',
								image: 'step-connect.png',
								// content: ['1、寻找到电子检测盒上二维码；', '2、请点击下方扫一扫；', '3、扫描二维码进行蓝牙连接。'],
								content: ['1、寻找到阅读仪上二维码；', '2、请点击下方扫一扫；', '3、扫描二维码进行蓝牙连接。'],
							}
						],
						operateName: '扫一扫',
					},
					// 连接失败
					{
						step: 2, // 5
						imageNum: 5,
						// name: '连接电子检测盒',
						name: '连接阅读仪',
						contentTitle: '请按以下说明进行检查',
						image: 'step-fail.png',
						imageDesc: '连接失败！',
						// content: ['1、保持电子检测盒在开机状态；', '2、检查手机蓝牙，保持开启状态；', '3、将手机与电子检测盒尽量靠近，完成蓝牙配对；',
						// 	'4、电子检测盒未连接到其他的手机。'],
							content: ['1、保持阅读仪在开机状态；', '2、检查手机蓝牙，保持开启状态；', '3、将手机与阅读仪尽量靠近，完成蓝牙配对；',
								'4、阅读仪未连接到其他的手机。'],
						operateName: '重新扫描',
					},
					// 连接成功
					{
						step: 3, // 6
						imageNum: 6,
						// name: '连接电子检测盒',
						name: '连接阅读仪',
						image: 'step-success.png',
						custom: true,
						imageDesc: '连接成功！',
						// operateName: '开始检测',
						operateName: '扫描配套试剂UDI码',
					},
					{
						step: 4, // 7
						imageNum: 7,
						// name: '指尖血采集',
						name: '匹配到配套试剂批次信息',
						image: 'step-collection.png',
						// content: ['先用酒精棉片擦拭取血部位，待酒精挥发后采用一次性采血针刺破皮肤采血，用滴管吸取血液。'],
						content: '',
						shengchanshijian: '',
						youxiaoqizhi: '',
						shijipihao: '',
						operateName: '开始检测',
					},
					{
						step: 5, // 8
						imageNum: 8,
						name: '加样检测',
						image: 'step-add.png',
						content: ['用滴管吸取一定量的血液样本，然后垂直滴入2滴样本（约 50μl）到加样孔中，并滴加两滴（约 80μl）缓冲液。'],
						operateName: '开始检测',
					},
					{
						step: 6, // 9
						imageNum: 9,
						name: '倒计时',
						contentTitle: '请按以下说明进行',
						// content: ['1、请保持电子检测盒平放，耐心等待；', '2、请勿退出应用程序；', '3、请勿将手机拿开检测仪超过50cm的距离。'],
						content: ['1、请保持阅读仪平放，耐心等待；', '2、请勿退出应用程序；', '3、请勿将手机拿开检测仪超过50cm的距离。'],
						operateName: '',
						timer: 0
					},
					{
						step: 7, // 10
						imageNum: 10,
						name: '检测结果',
						contentTitle: '检测结果说明',
						// content: ['检测完成后，请将电子检测盒、滴管以及其他组件放置于废弃物袋中，并密封。'],
						content: ['检测完成后，请将阅读仪、滴管以及其他组件放置于废弃物袋中，并密封。'],
						operateName: '',
						result: 0
					}
				]
			}
		},
		onUnload() {
			// that = this
			this.step = 1
			this.resultTimer = null
			this.timer = null
			this.close()
		},
		onBackPress(e) {
			console.log('onBackPress ', e)
			// backbutton 是点击物理按键返回，navigateBack是uniapp中的返回（比如左上角的返回箭头）
			if (['backbutton', 'navigateBack'].includes(e.from)) {
				if (that.step > 1) {
					if ([6].includes(that.step)) {
						that.isBack = true
						that.step = 1
						that.info = that.stepData[that.step - 1]
						// this.$refs.testCheck.update()
						that.close()
						return
					} else if (that.step === 7) {
						that.isBack = true
						that.close()
						uni.reLaunch({
							url: '/pages/welcome/index'
						})
						return
					}else if(that.step===3){
						that.isBack = true
						that.step = 1
						that.info = that.stepData[0]
						// this.$refs.testCheck.update()
						that.close()
						return
					}
					that.step--
					that.info = that.stepData[that.step - 1]
					// this.$refs.testCheck.update()
					return true // 阻止返回
				} else {
					if (that.isStartDiscovery) {
						that.stopDiscovery()
					}
					uni.reLaunch({
						url: '/pages/welcome/index'
					})
					return true // 阻止返回
				}
			}
		},
		onLoad(op) {
			var sysInfo = uni.getSystemInfoSync(); // 获取系统信息
			if (sysInfo.platform == 'android') { // 判断是否为安卓系统
			 this.xitong ='android'
			  console.log('当前运行的是安卓系统');
			} else if (sysInfo.platform == 'ios') { // 判断是否为iOS系统
			this.xitong ='ios'
			  console.log('当前运行的是iOS系统');
			} else {
			  console.log('未知系统');
			}
			// this.getLocation()
			console.log('onLoad')
			// uni.removeStorageSync(this.saveBluetoothDevice_key)
			// 获取已保存的蓝牙设备列表
			this.getSaveBluetoothDevice()
			// this.blueDeviceList = []
			// console.log('blueDeviceList ', this.blueDeviceList)
			that = this
			this.info = this.stepData[0]
			this.step = 1
			//获取手机系统的信息（在这主要是获取状态栏和胶囊的高度）
			uni.getSystemInfo({
				success: (e) => {
					// this.compareVersion(e.SDKVersion, '2.5.0')
					let statusBar = 0
					let customBar = 0


					// #ifdef MP
					statusBar = e.statusBarHeight
					customBar = e.statusBarHeight + 45
					if (e.platform === 'android') {
						// this.$store.commit('SET_SYSTEM_IOSANDROID', false)
						customBar = e.statusBarHeight + 50
					}
					// #endif


					// #ifdef MP-WEIXIN
					statusBar = e.statusBarHeight
					// @ts-ignore
					const custom = wx.getMenuButtonBoundingClientRect()
					customBar = custom.bottom + custom.top - e.statusBarHeight
					// #endif

					// #ifdef APP-PLUS
					console.log('app-plus', e)
					statusBar = e.statusBarHeight
					customBar = e.statusBarHeight + 45
					// #endif


					// #ifdef H5
					statusBar = 0
					customBar = e.statusBarHeight + 45
					// #endif

					// 这里你可以自己决定存放方式，建议放在store中，因为store是实时变化的
					console.log('SET_STATUS_BAR', statusBar)
					console.log('SET_CUSTOM_BAR', customBar)
					console.log('SET_SYSTEM_INFO', e)
					this.statusBarHeight = statusBar
					this.navHeight = customBar
				}
			})
		},
		onShow() {
			this.logs = []
			console.log('step',this.step)
			console.log('stepData',this.stepData[this.step]);
			if (this.timer && this.step === 6) {
				this.read(HANDLE_0x9007) // 读取结果：0x9007返回的检测结果剩余时间
			}
		},
		methods: {
			checkGetLocation() {
				plus.android.requestPermissions(
					['android.permission.ACCESS_FINE_LOCATION'],
					function(resultObj) {
						if (resultObj.granted.length) {
							if (!this.gps) {
								this.getLocation()
							} else {
								this.locationTimer = setInterval(() => {
									this.showCamera()
								}, 1500)
								
							}
						}
					}
				)
			},
			showCamera() {
				this.onConfirm()
				//第二个弹框暂时注释掉，如果上架不过审再加上
				// uni.showModal({
				// 	title: '温馨提示',
				// 	content: '为扫描设备二维码连接设备，需要开启相机功能',
				// 	success: (res) => {
				// 		if (res.confirm) {
				// 			this.onConfirm()
				// 		}
				// 	}
				// })
			},
			getLocation() {
				// checkOpenGPSServiceByAndroid()
				// permision.judgeIosPermission("location")
				uni.getLocation({
					type: 'wgs84',
					success: async (res) => {
						const response = await ConvertCoordinate({
							Locations: [res.longitude, res.latitude].join(',')
						})
						console.log('regeocode', response.Data.regeocode)
						if (response.Code === 200) {
							if (this.locationTimer) {
								clearInterval(this.locationTimer)
							}
							const {
								province,
								city,
								district
							} = response.Data.regeocode.addressComponent
							const address = response.Data.regeocode.formatted_address
							this.$store.commit('$uStore', {
								name: 'vx_city',
								value: {
									province,
									city,
									district,
									address
								}
							})
							this.gps = true
							this.showCamera()
						}
					},
					fail: (err) => {
						console.log(err)
						this.gps = false
						uni.showModal({
							title: '提示',
							content: '使用本设备时，请开启手机定位！',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									console.log('用户点击确定');
									checkOpenGPSServiceByAndroid()
								}
							}
						});
					}
				});
			},
			requestPermission() {
			    plus.android.requestPermissions(  
			    ["android.permission.CAMERA", "android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN", "android.permission.ACCESS_COARSE_LOCATION"],  
			    function(resultObj){  
			        for (var i = 0; i < resultObj.granted.length; i++) {  
			            var grantedPermission = resultObj.granted[i];  
			            console.log('已获取的权限：'+ grantedPermission);  
			        }  
			        for (var i = 0; i < resultObj.deniedPresent.length; i++) {  
			            var deniedPresentPermission = resultObj.deniedPresent[i];  
			            console.log('拒绝本次申请的权限：'+ deniedPresentPermission );  
			        }  
			        for (var i = 0; i < resultObj.deniedAlways.length; i++) {  
			            var deniedAlwaysPermission = resultObj.deniedAlways[i];  
			            console.log('永久拒绝申请的权限：'+ deniedAlwaysPermission);  
			        }  
			        // 若所需权限被永久拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限  
			        if (resultObj.deniedAlways.length > 0) {  
			            var Intent = plus.android.importClass("android.content.Intent");  
			            var Settings = plus.android.importClass("android.provider.Settings");  
			            var Uri = plus.android.importClass("android.net.Uri");  
			            var mainActivity = plus.android.runtimeMainActivity();  
			            var intent = new Intent();  
			            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);  
			            var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);  
			            intent.setData(uri);  
			            mainActivity.startActivity(intent);  
			        }  
			    },  
			    function(error){  
			        console.log('申请权限错误：'+ error.code+ " = "+ error.message);  
			    });  
			},
			customLog(...args) {
				const value = args.map(item => {
					if (typeof item === 'object') {
						return JSON.stringify(item)
					}
					return item
				})
				console.log(args)
				this.logs.push({
					time: new Date().getTime(),
					value: value.join(' ')
				})
			},
			toggleLog() {
				this.$refs.log.open('center')
				console.log(this.logs)
			},
			closeLog() {
				this.customLog('closeLog')
				this.$refs.log.close()
			},
			back: debounce(() => {
				console.log('that', that)
				console.log(that.step)
				that.customLog('back', that.step)
				if (that.step === 1) {
					uni.reLaunch({
						url: '/pages/welcome/index'
					})
					return
				} else if ([3, 6].includes(that.step)) {
					that.isBack = true
					that.step = 1
					that.info = that.stepData[that.step - 1]
					that.close()
					return
				} else if (that.step === 7) {
					that.isBack = true
					that.close()
					uni.reLaunch({
						url: '/pages/welcome/index'
					})
					return
				}
				that.step--
				that.info = that.stepData[that.step - 1]
			}, 500),
			onConfirm: debounce(async () => {
				console.log(that.step)
				if (that.step === 1) {
					if (that.gps === false) {
						console.log('当前未授权定位');
						uni.showModal({
							title: '温馨提示',
							content: '软件内在登陆后获取位置信息权限，用于在检测数据上传时同步定位患者位置信息，根据位置提供附近的医疗机构信息，期间保证用户信息的安全性，不用于其他方面。\n软件内调用了手机的相机功能，用于配合扫描设备二维码，软件内有相应的引导操作示意图，调用相机只起到扫描二维码连接蓝牙的作用。',
							success: (res) => {
								if (res.confirm) {
								that.requestPermission()
									that.getLocation()
								}
							}
						})
					} else if (that.gps === true) {
						// uni.showToast({
						// 	title: '正在寻找设备',
						// 	icon: 'none'
						// })
						// 扫码
						// if (that.isStartScan) return
						uni.scanCode({
							onlyFromCamera: true,
							success: (res) => {
								console.log('scanCode ', res)
								that.customLog('scanCode ', res)
								const result = res.result
								that.scanDeviceName = result.split(',')[1]
								that.scanMac = result.split(',')[0]
								// if (!result.includes('XHA')) {
								// 	uni.showModal({
								// 		content: '请扫描正确二维码',
								// 		showCancel: false
								// 	})
								// 	return
								// }
								console.log('scanMac = ', that.scanMac)
								that.customLog('scanMac = ', that.scanMac)
								const city = that.$store.state.vx_city
								if (that.scanDeviceName.length < 9) {
									that.deviceNumber = that.scanDeviceName.padStart(9, '0')
								} else {
									that.deviceNumber = that.scanDeviceName
								}
								CreateReagentResult({
									DeviceNo: that.deviceNumber,
									MacNo: that.scanMac,
									// DetectionType: this.DetectionType,
									// DetectionTime: new Date(),
									Phone: that.$store.state.vx_u_info.Phone,
									Province: city.province,
									City: city.city,
									County: city.district,
									Address: city.address,
									Street: city.township,
									// DetectionResult: arg1,
									// Yuzhi:yuzhi,
									// Jieguozhi:jieguozhi,
									type: platform === 'android' ? '安卓' : 'IOS'
								}).then(res => {
									console.log('CreateReagentResult', res)
									that.customLog('CreateReagentResult', res)
								}).catch(e => {
									console.log('CreateReagentResult error', e)
									that.customLog('CreateReagentResult error', e)
								})
								// 连接蓝牙
								that.initBlue()
							},
							complete: () => {
								// that.isStartScan = true
							}
						})
					}
				} else if (that.step === 2) {
					that.step = 1
					that.info = that.stepData[that.step - 1]
				} else if (that.step === 3) {
					that.read(HANDLE_0x9003)
					uni.scanCode({
						onlyFromCamera: true,
						success: (res) => {
							console.log('scanCode ', res.result)
							let picihao = (res.result).slice(-13)
							let a = '20' + (res.result).substring(19, 25)
							let b = '20' + (res.result).substring(27, 33)
							let c = a.substring(0, 4) + '-' + a.substring(4)
							let d = b.substring(0, 4) + '-' + b.substring(4)
							let shengchanshijian = c.substring(0, 7) + '-' + c.substring(7)
							let youxiaoqizhi = d.substring(0, 7) + '-' + d.substring(7)
							console.log(shengchanshijian, '生产日期');
							console.log(youxiaoqizhi, '有效期至');
							console.log(that.deviceNumber, '设备编号');
							console.log(picihao, '批次号');
							UDI({
								EffectTime: shengchanshijian,
								FailureTime: youxiaoqizhi,
								// Deviceno: that.deviceNumber,
								Reagentno: picihao,
							}).then(res => {
								console.log(res);
								if (res.Code == 200) {  
									that.stepData[3].shengchanshijian=((res.Data.EffectTime).slice(0,10)).replace(/-/g, '.')
									that.stepData[3].youxiaoqizhi= ((res.Data.FailureTime).slice(0,10)).replace(/-/g, '.')
									that.stepData[3].shijipihao= res.Data.Reagentno
									that.Reagentno=res.Data.Reagentno
									console.log(that.stepData[3],'当前UDI值');
									that.step++
									that.info = that.stepData[that.step - 1]
								} else {
									uni.showToast({
										title: `未匹配到批次号信息`,
										icon: 'none',
										duration: 4000
									})
								}

							}).catch(err => {
								console.log(err);
								uni.showToast({
									title: `请扫描正确二维码`,
									icon: 'none',
									duration: 4000
								})
							})

						},
						complete: () => {
							// that.isStartScan = true
						}
					})
				} else if (that.step === 4) {
					that.step++
					that.info = that.stepData[that.step - 1]
				} else if (that.step === 5) { // 开始检测
					if (that.resultTimer) {
						clearTimeout(that.resultTimer)
					}
					// that.serviceId = HANDLE_0x9000
					// await sleep(1000)
					// that.read(HANDLE_0x9001)
					//
					// this.notify(HANDLE_0x9002) // 读取结果：0x9002返回的检测项目
					// await sleep(1000)
					// this.read(HANDLE_0x9002)
					//

					// that.read(HANDLE_0x9003)
					// await sleep(500)

					// that.notify(HANDLE_0x9004) // 读取结果：0x9004返回的检测状态

					that.read(HANDLE_0x9004)
				} else if (that.step === 7) {
					that.isBack = true
					that.close()
					uni.navigateTo({
						url: '/pages/welcome/index'
					})
				}
			}, 500),
			onAdapter() {
				console.log('启动-适配器-监听器');
				uni.onBluetoothAdapterStateChange((e) => {
					console.log('监听到适配器的状态 =》', JSON.stringify(e))
					this.customLog('监听到适配器的状态 =》', JSON.stringify(e))
					this.bleAdapter = e
					if (e.available === false && this.isBack === false) {
						this.bleConnection = false
						this.step = 2
						this.info = this.stepData[this.step - 1]
						// this.$refs.testCheck.update()
						console.log('适配器不可用')
						this.customLog('适配器不可用')
						// #ifdef MP-WEIXIN
						uni.showToast({
							title: `蓝牙适配器不可用`,
							icon: 'none',
							duration: 2000
						})
						// #endif
						uni.closeBluetoothAdapter({
							success: (res) => {
								console.log('关闭蓝牙适配器成功')
								this.customLog('关闭蓝牙适配器成功')
								console.log(res)
							}
						})
					}
				})
			},
			onConnection() {
				console.log('启动-连接状态-监听器');
				this.customLog('启动-连接状态-监听器');
				uni.onBLEConnectionStateChange((e) => {
					this.bleConnection = e.connected
					if (this.bleConnection === false && this.isBack === false) {
						this.bleAdapter = {
							available: false
						}
						this.step = 2
						this.info = this.stepData[this.step - 1]
						// this.$refs.testCheck.update()
						this.customLog('连接失败')
						// #ifdef MP-WEIXIN
						uni.showToast({
							title: `与蓝牙设备连接失败`,
							icon: 'none',
							duration: 2000
						})
						// #endif
						if (this.isStartDiscovery) {
							uni.closeBluetoothAdapter({
								success: (res) => {
									this.customLog('关闭蓝牙适配器成功')
									console.log(res)
								}
							})
						}
						if (this.timer) {
							clearInterval(this.timer)
						}
					}
					this.customLog('监听到蓝牙设备连接的状态 =》', JSON.stringify(e))
				})
			},
			//获取已保存的蓝牙设备列表
			getSaveBluetoothDevice() {
				this.blueDeviceList = uni.getStorageSync(this.saveBluetoothDevice_key) || []
				console.log('本地记录 已保存过的蓝牙设备列表', this.blueDeviceList)
			},
			// 初始化
			initBlue() {
				// this.isStartScan = false
				if (this.isBack) {
					this.isBack = false
				}
				if (this.isStartDiscovery) {
					uni.stopBluetoothDevicesDiscovery({
						success: (res) => {
							this.customLog('停止搜索')
							console.log(res)
						}
					})
					uni.closeBluetoothAdapter({
						success: (res) => {
							this.customLog('关闭蓝牙适配器成功')
							console.log(res)
						}
					})
				}
				uni.openBluetoothAdapter({
					success: (res) => {
						this.customLog('初始化蓝牙成功', res)
						this.bleAdapter = {
							available: true
						};
						this.onAdapter()
						this.discovery()
					},
					fail: (err) => {
						uni.showModal({
							title: '提示',
							content: '请开启手机蓝牙！',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									this.customLog('用户点击确定');
									uni.closeBluetoothAdapter({
										success: (res) => {
											this.customLog('关闭蓝牙适配器成功')
											console.log(res)
										}
									})
								}
							}
						});
						this.customLog('初始化蓝牙失败')
						console.error(err)
					}
				})
			},
			// 开始搜寻附近设备
			discovery() {
				if (!this.bleAdapter.available) {
					this.initBlue();
					return
				}
				uni.startBluetoothDevicesDiscovery({
					services: ['00009000-0000-1000-8000-00805F9B34FB'],
					success: (res) => {
						this.isStartDiscovery = true
						this.customLog('开始搜索')
						setTimeout(() => {
							if (this.isStartDiscovery) {
								this.stopDiscovery()
								uni.showToast({
									title: '未找到蓝牙设备',
									icon: 'none'
								})
							}
						}, 30000)
						
						uni.showToast({
							title: '正在寻找蓝牙',
							icon: 'none'
						});
						
						// 开启监听回调
						this.executeMethods()
						
						// uni.onBluetoothDeviceFound(this.found)

						// if (this.blueDeviceList.length) {
						// 	this.setConnect()
						// }
					},
					fail: (err) => {
						this.isStartDiscovery = false
						this.customLog('搜索失败')
						console.error(err)
					}
				})
			},
			//附近设备
			executeMethods() {
				// 开启监听回调
				uni.onBluetoothDeviceFound(this.found)
				uni.showToast({
					title: '正在搜索蓝牙...',
					icon: 'none',
					duration: 3000
				})
				// 3秒后执行方法2
				setTimeout(() => {
					this.stopDiscovery()
					this.customLog(this.blueDeviceList, '找到设备');
					this.customLog('当前设备编号', this.scanMac);
					this.blueDeviceList.forEach(item => {
						this.customLog(item);
						// console.log((item.localName).substring(3),'遍历设备号');
						if ((item.localName).substring(3) == this.scanMac) {
							this.blueDeviceList_1.push(item);
							this.customLog('配对成功', this.blueDeviceList_1);
							//开始连接
							this.setConnect()
						}
					})
				}, 3000);
			},
			// 找到新设备就触发该方法
			found(res) {
				
				if(this.xitong ==='android'){
					console.log(res,'安卓found测试');
					if(res.devices[0].advertisData){
						 if (!this.blueDeviceList.find(item => item.deviceId === res.devices[0].deviceId)) {
						 	this.blueDeviceList.push(res.devices[0]);
						 }
					 }
					console.log('当前设备数组',this.blueDeviceList);
				}else if(this.xitong ==='ios'){
					console.log(res,'苹果found测试');
						if (res.devices.length) {
							if (res.devices[0].deviceId) {
								if (res.devices[0].localName.includes('XH') || (res.devices[0].advertisServiceUUIDs.length && res
										.devices[0].advertisServiceUUIDs[0] === HANDLE_0x9000)) {
									this.customLog('苹果found ', res.devices[0])
									this.blueDeviceList.push(res.devices[0])
								}
							}
						}
					console.log('当前设备数组',this.blueDeviceList);
				}
			    
			},
			// found(res) {
			// 	// this.customLog(res)
			// 	// console.log('devices', res.devices)
			// 	if (res.devices.length) {
			// 		if (res.devices[0].deviceId) {
			// 			if (res.devices[0].localName.includes('XH') || (res.devices[0].advertisServiceUUIDs.length && res
			// 					.devices[0].advertisServiceUUIDs[0] === HANDLE_0x9000)) {
			// 				this.customLog('found ', res.devices[0])
			// 				this.blueDeviceList.push(res.devices[0])
			// 				this.setConnect()
			// 			}
			// 		}
			// 	}
			// },
			
			// 循环设备列表，找到对应的设备
			setConnect() {
				this.blueDeviceList_1.forEach(item => {
					// 区分ios Android
					// let platform = uni.getSystemInfoSync().platform
					// this.customLog('blueDeviceList ', item)
					console.log('blueDeviceList ', item)
					// const uuid = item.advertisServiceUUIDs[0]
					let mac = ''
					if (item.isConnected) {
						mac = item.mac
					} else {
						const advertisData = ab2hex(item.advertisData)
						mac = advertisData.toUpperCase()
					}
					// console.log('service uuid/mac =', uuid, mac)
					// this.customLog('service uuid/mac =', uuid, mac)
					console.log('mac = ', mac)
					this.customLog('mac = ', mac)
					this.customLog('localName = ', item.localName)
					this.customLog('当前设备号 ', this.deviceNumber)
					var Deviceno_num = (this.deviceNumber).toString()
					if (mac.length === 24) {
						//新板子
						uni.request({
							url: `https://jinan.shlxkj.info:8010/api/Decrypt/decryptMac`,
							method: 'GET',
							data: {
								macCode: mac
							},
							header: {
								Authorization: 'Bearer ' + this.$store.state.vx_token,
								ApiKey: this.$store.state.vx_token
							},
							success: (res) => {
								
								if (res.data.Code === 200) {
									console.log('接口解码', res.data.Data);
									this.customLog('接口解码', res.data.Data);
									let mac_base64 = res.data.Data
									if (mac_base64.includes(this.scanMac)) {
										item.mac = res.data.Data
										console.log('本板子解码后的mac地址', mac_base64);
										this.customLog('本板子解码后的mac地址', mac_base64);
										let phonenumber = this.$store.state.vx_u_info.Phone
										//查询是否存在关联
										GetReleted({
											mac: mac_base64,
										}).then(res => {
											console.log(res.Data);
											this.customLog(res.Data);
											let arr = res.Data
											console.log('现在的号码', phonenumber);
											this.customLog('现在的号码', phonenumber);
											console.log('绑定的号码', res.Data[0]?.Number);
											this.customLog('绑定的号码', res.Data[0]?.Number);
											if (arr.length == 0) {
												console.log('没有绑定');
												this.customLog('没有绑定');
												CreateReleted({
													Mac: mac_base64,
													Number: this.$store.state.vx_u_info
														.Phone,
														Deviceno:Deviceno_num
												}).then(res => {
													console.log('新增结果', res);
													this.customLog('新增结果', res);
													if (res.Code == 200) {
														uni.showToast({
															title: '正在连接',
															icon: 'success',
															duration: 2000
														})
														// this.stopDiscovery()
														this.bleConnect(item)
														this.blueDeviceList_1=[]
													}
												})
											} else {
												if (arr[0].Number == phonenumber) {
													console.log('绑定机链接');
													this.customLog('绑定机链接');
													uni.showToast({
														title: '正在连接',
														icon: 'success',
														duration: 2000
													})
													// this.stopDiscovery()
													this.bleConnect(item)
													this.blueDeviceList_1=[]
												} else {
													uni.showToast({
														title: '本设备已被绑定',
														icon: 'error',
														duration: 2000
													})
												}
											}
										})
									}
								}
							}
						})
					} else if (mac.includes(this.scanMac)) {
						item.mac = mac
						let phonenumber = this.$store.state.vx_u_info.Phone
						GetReleted({
							mac: mac,
						}).then(res => {
							console.log(res.Data);
							let arr = res.Data
							console.log('现在的号码-老板子', phonenumber);
							this.customLog('现在的号码-老板子', phonenumber);
							// console.log('绑定的号码',res.Data[0].Number);
							if (arr.length == 0) {
								console.log('没有绑定');
								this.customLog('没有绑定');
								CreateReleted({
									Mac: mac,
									Number: this.$store.state.vx_u_info.Phone,
									Deviceno:Deviceno_num
								}).then(res => {
									console.log('新增结果', res);
									this.customLog('新增结果', res);
									if (res.Code == 200) {
										uni.showToast({
											title: '正在连接',
											icon: 'success',
											duration: 2000
										})
										// this.stopDiscovery()
										this.bleConnect(item)
										this.blueDeviceList_1=[]
									}
								})
							} else {
								if (arr[0].Number == phonenumber) {
									console.log('绑定机链接');
									this.customLog('绑定机链接');
									uni.showToast({
										title: '正在连接',
										icon: 'success',
										duration: 2000
									})
									// this.stopDiscovery()
									this.bleConnect(item)
									this.blueDeviceList_1=[]
								} else {
									uni.showToast({
										title: '本设备已被绑定',
										icon: 'error',
										duration: 2000
									})
								}
							}
						})
					} else if (item.localName.includes(' ')) {
						const localMac = item.localName.split(' ')[1]
						console.log(localMac)
						this.customLog('localMac ', localMac)
						if (localMac.includes(this.scanMac)) {
							let phonenumber = this.$store.state.vx_u_info.Phone
							item.mac = localMac
							GetReleted({
								mac: localMac,
							}).then(res => {
								console.log(res.Data);
								let arr = res.Data
								console.log('现在的号码-老板子', phonenumber);
								this.customLog('现在的号码-老板子', phonenumber);
								// console.log('绑定的号码',res.Data[0].Number);
								if (arr.length == 0) {
									console.log('没有绑定');
									CreateReleted({
										Mac: localMac,
										Number: this.$store.state.vx_u_info.Phone,
										Deviceno:Deviceno_num
									}).then(res => {
										console.log('新增结果', res);
										this.customLog('新增结果', res);
										if (res.Code == 200) {
											uni.showToast({
												title: '正在连接',
												icon: 'success',
												duration: 2000
											})
											// this.stopDiscovery()
											this.bleConnect(item)
											this.blueDeviceList_1=[]
										}
									})
								} else {
									if (arr[0].Number == phonenumber) {
										console.log('绑定机链接');
										this.customLog('绑定机链接');
										uni.showToast({
											title: '正在连接',
											icon: 'success',
											duration: 2000
										})
										// this.stopDiscovery()
										this.bleConnect(item)
										this.blueDeviceList_1=[]
									} else {
										uni.showToast({
											title: '本设备已被绑定',
											icon: 'error',
											duration: 2000
										})
									}
								}
							})
						}
					}
				})
			},
			// 连接蓝牙
			async bleConnect(data) {
				if (this.scanDeviceName.length < 9) {
					this.deviceNumber = this.scanDeviceName.padStart(9, '0')
				} else {
					this.deviceNumber = this.scanDeviceName
				}
				uni.createBLEConnection({
					deviceId: data.deviceId,
					success: async (res) => {
						// this.saveDevice({
						// 	isConnected: true,
						// 	mac: data.mac,
						// 	...data
						// })
						this.customLog('连接成功', data)
						this.step = 3
						this.$set(this, 'info', this.stepData[this.step - 1])
						console.log(this.$refs)
						this.$forceUpdate
						console.log('info ', this.info)
						this.deviceId = data.deviceId
						this.serviceId = HANDLE_0x9000
						console.log(this.deviceId + '==>', HANDLE_0x9000)
						this.customLog(this.deviceId + '==>', HANDLE_0x9000)
						if (data.localName.includes(' ')) {
							this.DetectionType = data.localName.split(' ')[0]
						} else {
							this.DetectionType = data.localName
						}
						this.onConnection()
						await sleep(1000)
						this.getServices()
					},
					fail: async (err) => {
						console.log('连接失败', err)
						this.customLog('连接失败', err)
						if (err.errno === 1509007 || err.errMsg ===
							'createBLEConnection:fail already connect') {
							// uni.showToast({
							//   title: `蓝牙设备已连接`,
							//   icon: 'success',
							//   duration: 2000
							// })
							// this.deviceNumber = this.scanDeviceName.padStart(9, '0')
							this.step = 3
							this.$set(this, 'info', this.stepData[this.step - 1])
							this.$forceUpdate
							console.log('info', this.info)
							this.deviceId = data.deviceId
							this.serviceId = HANDLE_0x9000
							this.DetectionType = data.localName
							await sleep(1000)
							this.getServices()
						} else {
							if (this.isBack === true) return
							this.step = 2
							this.info = this.stepData[this.step - 1]
							// this.$refs.testCheck.update()
							uni.showToast({
								title: `与蓝牙设备连接失败`,
								icon: 'none',
								duration: 2000
							})
							console.error(err)
							uni.closeBluetoothAdapter({
								success: (res) => {
									console.log('关闭蓝牙适配器成功')
									console.log(res)
								}
							})
						}
					}
				})
			},
			// 停止搜索
			stopDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: (res) => {
						this.isStartDiscovery = false
						console.log('停止成功', res)
						this.customLog('停止成功', res)
						// uni.stopBluetoothDevicesDiscovery({
						//   success: (res) => {
						//     console.log('停止搜索')
						//     console.log(res)
						//   }
						// })
					},
					fail: (err) => {
						console.log('停止失败')
						this.customLog('停止失败')
						console.error(err)
					}
				})
			},
			// 获取服务
			getServices() {
				uni.getBLEDeviceServices({
					deviceId: this.deviceId, // 设备ID，在上一步【4】里获取
					success: async (res) => {
						console.log(res)
						// 先获取key
						// this.serviceId = HANDLE_0x1800
						this.getCharacteristics()
						// await sleep(1000)
						// this.read(HANDLE_0x2A00)
						// console.log(this.deviceId + '==>', HANDLE_0x2A00)
					},
					fail: (err) => {
						console.error(err)
						if (this.timer) {
							clearInterval(this.timer)
							this.timer = null
						}
						if ([-1, 10000, 10002, 10003, 10004, 10005, 10006].includes(err.errCode)) {
							this.close()
							uni.showModal({
								content: '请检查设备是否正常运行，或重新扫描连接。',
								showCancel: false,
								success(res) {
									if (res.confirm) {
										that.step = 1
										that.info = that.stepData[that.step - 1]
									}
								}
							})
						}
					}
				})
			},
			// 获取特征值
			getCharacteristics() {
				uni.getBLEDeviceCharacteristics({
					deviceId: this.deviceId, // 设备ID
					serviceId: this.serviceId, // 服务UUID
					success: (res) => {
						console.log('characteristics =', res)
					},
					fail: (err) => {
						console.error(err)
						if ([10002, 10003, 10006].includes(err.errCode) || err.code === 10004) {
							this.close()
							uni.showModal({
								content: '请检查设备是否正常运行，或重新扫描连接。',
								showCancel: false,
								success(res) {
									if (res.confirm) {
										that.step = 1
										that.info = that.stepData[that.step - 1]
									}
								}
							})
						}
					}
				})
			},
			// 【8】开启消息监听
			notify(characteristicId) {
				console.log(characteristicId)
				uni.notifyBLECharacteristicValueChange({
					deviceId: this.deviceId, // 设备ID，在【4】里获取到
					serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
					characteristicId, // 特征值，在【7】里能获取到
					state: true, // 启用消息监听
					success: (res) => {
						console.log(res)
						// 接受消息的方法
						this.listenValueChange()
					},
					fail: async (err) => {
						console.log('开启消息监听失败')
						console.error(err)
					}
				})
			},
			// 监听消息变化
			listenValueChange() {
				this.valueChangeTimes = 0
				uni.onBLECharacteristicValueChange(async res => {
					this.valueChangeFn(res)
				})
			},
			// 监听消息变化
			valueChangeFn: debounce(async (res) => {
				console.log('listenValueChange 开始')
				/**
				 * {characteristics: [
				 * {properties:  { writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009001-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009002-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009003-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: true, notify: true, write: true, indicate: false, read: true, writeNoResponse: false}, uuid: "00009004-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: true, notify: false, write: true, indicate: false, read: true, writeNoResponse: false}, uuid: "00009005-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009006-0000-1000-8000-00805F9B34FB"},
				 * {properties: {writeDefault: false, notify: false, write: false, indicate: false, read: true, writeNoResponse: false}, uuid: "00009007-0000-1000-8000-00805F9B34FB"}],
				 * deviceId: "3DB85199-BEE5-A05C-E67A-29F303ABA225", serviceId: "00009000-0000-1000-8000-00805F9B34FB", errno: 0, errMsg: "getBLEDeviceCharacteristics:ok", errCode: 0}
				 */
				that.valueChangeTimes++
				console.log('valueChangeTimes => ', that.valueChangeTimes)
				console.log('onBLECharacteristicValueChange', res)
				// 结果里有个value值，该值为 ArrayBuffer 类型，所以在控制台无法用肉眼观察到，必须将该值转换为16进制
				const resHex = ab2hex(res.value)
				console.log('ab2hex ===', resHex)
				if (res.characteristicId === HANDLE_0x9001) {
					const data = await that.aesDecrypt(resHex, '0x9001')
					console.log("读取结果：0x9001返回的唯一编号" + data);
					// 句柄0x9002对应检测项目(ASCII码16个字节)，
				} else if (res.characteristicId === HANDLE_0x9002) {
					const data = await that.aesDecrypt(resHex, '0x9002')
					console.log("读取结果：0x9002返回的检测项目" + data);
					// 句柄0x9003对应批次号(ASCII码8个字节)，
				} else if (res.characteristicId === HANDLE_0x9003) {
					// const data = await that.aesDecrypt(resHex, '0x9003')
					// console.log("读取结果：0x9003返回的批次号" + data);
					const num = resHex.substr(-18)
					that.key = baseSecret + num
					console.log('key => ', that.key)
					// 句柄0x9004对应检测状态(1个字节)，
				} else if (res.characteristicId === HANDLE_0x9004) {
					const data = await that.aesDecrypt(resHex, '0x9004')
					console.log("读取结果：0x9004返回的检测状态" + data);
					that.step = 6
					that.info = that.stepData[that.step - 1]
					if (1 === data) {
						console.log("读取结果：0x9004返回的=" + data + "=已开始检测，继续读取倒计时");
						that.read(HANDLE_0x9007) // 读取结果：0x9007返回的检测结果剩余时间
					} else {
						that.times = -1
						console.log("读取结果：0x9004返回的：" + data + "==" + (0 === data ? "未开始检测" : "未知状态") +
							",等待5秒后重新查询状态");
						console.log('resultTimer', that.resultTimer)
						if (that.resultTimer) {
							clearTimeout(that.resultTimer)
						}
						that.resultTimer = setTimeout(function() {
							if (that.resultTimer) {
								clearTimeout(that.resultTimer)
							}
							that.read(HANDLE_0x9004)
						}, 5000)
					}
					// 句柄0x9005对应检测结果(5个字节，1个字节为结果，四个字节为过程数据)，结果为0为阴性，1为阳性，2为异常。
				} else if (res.characteristicId === HANDLE_0x9005) {
					if (that.processIndex === 0) {
						const data = await that.aesDecrypt(resHex, '0x9005')
						let {
							arg1: real
						} = data // 0 阴性 1 阳性 2 异常
						
						let {
							arg1: real2
						} = data // 0 阴性 1 阳性 2 异常
						that.customLog("读取结果：0x9005返回的检测结果" + real2);
						
						const jieguozhiRes = await aesDecryptjieguozhi({
							Data: resHex,
							Key: that.key,
							Handle: '0x9005'
						})
						that.customLog('9005X结果值返回', jieguozhiRes.Data.jieguozhi);
						that.$store.commit('$uStore', {
							name: 'jieguozhi',
							value: jieguozhiRes.Data.jieguozhi
						})
						that.customLog('存入的结果值', that.$store.state.jieguozhi);

					
						await aesDecryptGetAPiyuzhi({reagentno:that.Reagentno}).then(res=>{
							console.log('动态阈值获取阈值',res.Data[0]?.Yuzhi);
							that.$store.commit('$uStore', {
								name: 'houtaiyuzhi',
								value: res.Data[0]?.Yuzhi
							})
							if(res.Data[0]?.Yuzhi==undefined){
								console.log('接口无返回阈值');
							}else{
									if(res.Data[0].Yuzhi>that.$store.state.jieguozhi){
										console.log('结果值小于与阈值，阴性');
										real =0
									}else if(res.Data[0].Yuzhi<=that.$store.state.jieguozhi){
										console.log('结果值大于与阈值，阳性');
										real =1
									}
								}
						})
						// const arg1 = Number(jieguozhiRes.Data.jieguozhi) > Number(yuzhiRes.Data) ? 1 : 0
						// that.result = arg1
						that.step = 7
						const info = that.stepData[that.step - 1]
						if (real == 2) {
							that.info = Object.assign({}, info, {
								result: real,
								operateName: '返回'
							})
						}else{
							if (real === 1) {
								that.info = Object.assign({}, info, {
									result: real,
									operateName: '返回'
								})
							}else{
								that.info = Object.assign({}, info, {
									result: real,
									operateName: '返回'
								})
							}
						}
					
						
						// if (real == 2) {
						// 	that.info = Object.assign({}, info, {
						// 		result: real,
						// 		operateName: '返回'
						// 	})
						// } else {
						// 	if (arg1 === 1) {
						// 		that.info = Object.assign({}, info, {
						// 			result: arg1
						// 		})
						// 	} else {
						// 		that.info = Object.assign({}, info, {
						// 			result: arg1,
						// 			operateName: '返回'
						// 		})
						// 	}
						// }
						const city = that.$store.state.vx_city
						console.log('下面读取9006');
						that.customLog('下面读取9006');
						const yuzhi = (that.$store.state.yuzhi).toString()
						const houtaiyuzhi = (that.$store.state.houtaiyuzhi).toString() 
						let jieguozhi = (that.$store.state.jieguozhi).toString()
						that.customLog('设备阈值', yuzhi);
						that.customLog('后台阈值', houtaiyuzhi);
						that.customLog('jieguozhi', jieguozhi);
						that.customLog('realdetectionresult', real);
						// that.customLog('detectionresult', arg1);
						try {
							const resp = await UpReagentResult({
								DeviceNo: that.deviceNumber,
								MacNo: that.scanMac,
								DetectionType: that.DetectionType,
								// DetectionTime: new Date(),
								Phone: that.$store.state.vx_u_info.Phone,
								Province: city.province,
								City: city.city,
								County: city.district,
								Address: city.address,
								Street: city.township,
								Yuzhi: houtaiyuzhi,//后台阈值
								Realyuzhi:yuzhi,//设备阈值
								Jieguozhi: jieguozhi,
								DetectionResult: real,//判断过的数据
								Realdetectionresult: real2,//真实数据
								type: platform === 'android' ? '安卓APP' : 'IOS APP',
							})
							if (resp.Code === 200 || resp.Code === 801) {
								console.log('上报成功结果 ===》', resp.Data)
								that.customLog('上报成功结果 ===》', resp.Data)
								if (real === 1) {
									// that.$refs.popup.open('center')
								}
							}
						} catch (e) {
							that.customLog('上报成功失败 ===》', e)
							console.log(e);
						}

						// let arg1 = 0
						// const testResult = uni.getStorageSync('testResult')
						// console.log('testResult', testResult, typeof testResult)
						// if ([0, 1].includes(testResult)) {
						//   arg1 = testResult
						// }
						// if (arg1 === 1) {
						//   setTimeout(() => {
						//     that.$refs.popup.open('center')
						//   }, 1500)
						//   that.info = Object.assign({}, info, { result: arg1 })
						// } else {
						//   that.info = Object.assign({}, info, { result: arg1, operateName: '返回' })
						// }
						// const city = that.$store.state.vx_city
						// console.log('下面读取9006');
						// let yuzhi =(that.$store.state.yuzhi).toString()
						// console.log(yuzhi);
						// const res = await CreateReagentResult({
						//   DeviceNo: that.deviceNumber,
						//   MacNo: that.scanMac,
						//   DetectionType: that.DetectionType,
						//   DetectionTime: new Date(),
						//   Phone: that.$store.state.vx_u_info.Phone,
						//   Province: city.province,
						//   City: city.city,
						//   County: city.district,
						//   Address: city.address,
						//   DetectionResult: arg1,
						//   Yuzhi: yuzhi,
						//   RealDetectionResult: String(real),
						// })
						// console.log('上报结果 ===》', res)
						// if (res.Code === 200) {
						//   console.log('上报成功结果 ===》', res.Data)
						// }
						// const ReportRes = await ReportedData({
						//   Result: arg1,
						//   DeviceNo: that.deviceNumber,
						//   Key: that.key,
						//   ReportedDatas: that.process.map(item => {
						//     return {
						//       Data: item
						//     }
						//   })
						// })
						// if (ReportRes.Code === 200) {
						//   console.log('上报过程完成')
						// }
					} else if (that.processIndex !== 0 && that.processIndex < 195) {
						console.log("读取过程值次数：", that.processIndex)
						that.process.push(resHex)
						that.processIndex++
						await that.read(HANDLE_0x9005) // 读取过程值：0x9005返回的检测结果
					} else if (that.processIndex >= 195) {
						// console.log("读取过程值次数结束：", that.processIndex)
						// that.process.push(resHex)
						// that.processIndex = 0
						// that.startWriteProgress()
					}
					// 句柄0x9006对应检测开始时间(4个字节，单位为秒，未开始为0，结束为0xffffffff)，
				} else if (res.characteristicId === HANDLE_0x9006) {
					const data = await that.aesDecrypt(resHex, '0x9006')
					console.log("读取结果：0x9006返回" + data);
					that.customLog("读取结果：0x9006返回" + data);
					await aesDecrypt2({
						Data: resHex,
						Key: that.key,
						Handle: '0x9006'
					}).then(res => {
						console.log('9006X阈值返回', res, res.Data.yz);
						that.customLog('9006X阈值返回', res, res.Data.yz);
						that.$store.commit('$uStore', {
							name: 'yuzhi',
							value: res.Data.yz
						})

						console.log('存入的阈值', that.$store.state.yuzhi);
						that.customLog('存入的阈值', that.$store.state.yuzhi);
						// console.log(this.$store.state.yuzhi);
					})

					// 句柄0x9007对应检测结果剩余时间(4个字节，单位为秒，未开始为0xffffffff，结束为0)。
				} else if (res.characteristicId === HANDLE_0x9007) {
					await that.read(HANDLE_0x9006)
					const data = await that.aesDecrypt(resHex, '0x9007')
					console.log("读取结果：0x9007返回的检测结果剩余时间" + data);
					that.times = data
					let end = Date.now() + (data + 1) * 1000;
					// 倒计时结束请求获取结果
					let times = data
					if (that.timer) {
						clearInterval(that.timer)
					}
					let isReport = false
					console.log("当前时间戳", Date.now() + "==" + end);
					that.timer = setInterval(async () => {
						times = parseInt((end - Date.now()) / 1000)
						console.log('倒计时', times)
						// that.getServices()
						if (times <= 0) {
							times = 1
							clearInterval(that.timer)
							that.timer = null
							// 开始读取过程值
							if (isReport) return
							that.processIndex = 0
							console.log('倒计时结束', times)
							// that.startWriteProgress()
							await that.read(HANDLE_0x9005)
							isReport = true
						}
					}, 1000)
				}
			}, 400),
			async startWriteProgress() {
				console.log('startWriteProgress ', this.processIndex)
				await this.send(HANDLE_0x9005, this.processIndex)
				// if (this.processIndex === 1) {
				//   this.notify(HANDLE_0x9005)
				// } else {
				// }
				this.read(HANDLE_0x9005)
			},
			// aes解密方法
			async aesDecrypt(word, handle) {
				// uni.showLoading({
				//   title: 'loading'
				// })
				const res = await AESDecrypt({
					Data: word,
					Key: this.key,
					Handle: handle
				})
				// uni.hideLoading()
				if (res.Code === 200) {
					return res.Data
				}
			},
			// aes加密方法
			async aesEncrypt(word) {
				const res = await AESEncrypt({
					Data: word,
					Key: this.key
				})
				if (res.Code === 200) {
					return res.Data
				}
			},
			// 向设备发送数据
			async send(characteristicId, type = 0) {
				console.log(`写入${characteristicId}，值为${type}`)
				let Data = ''
				if (type === 0) {
					Data = '00000000000000000000000000000000'
				} else {
					Data = '10000000000000000000000000000000'
				}
				const res = await AESEncrypt({
					Data,
					Key: this.key
				})
				console.log('写入', Data, res.Data)
				if (res.Code === 200) {
					const buffer = new ArrayBuffer(res.Data)
					uni.writeBLECharacteristicValue({
						deviceId: this.deviceId, // 设备ID，在【4】里获取到
						serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
						characteristicId, // 特征值，在【7】里能获取到
						value: buffer,
						success: async (res) => {
							// if (characteristicId === HANDLE_0x9005) {
							//   this.read(HANDLE_0x9005) // 读取结果：0x9005返回的检测结果
							// }
							console.log('写入指令发送成功', res)
							await sleep(100)
							await this.getCharacteristics()

						},
						fail: (err) => {
							console.log('写入指令发送失败', err)
						}
					})
				}
			},
			// 【11】读取数据
			read(characteristicId) {
				// console.log('read ', this.deviceId, this.serviceId)
				uni.readBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId,
					success: (res) => {
						console.log(`${ characteristicId }读取指令发送成功`)
						// 接受消息的方法
						this.valueChangeTimes = 0

						this.listenValueChange()
					},
					fail: (err) => {
						console.log('读取指令发送失败', err)
					}
				})
			},
			async close() {
				this.times = 0
				this.step = 1
				// if (this.resultTimer) {
				//   clearTimeout(this.resultTimer)
				//   this.resultTimer = null
				// }
				if (this.timer) {
					clearInterval(this.timer)
					this.timer = null
				}
				if (this.isStartDiscovery) {
					this.stopDiscovery()
				}
				if (this.$refs.testCheck) {
					this.$refs.testCheck.getReset()
				}
				this.$refs.popup.close()
				//断开蓝牙连接
				uni.closeBLEConnection({
					//设备ID
					deviceId: this.deviceId,
					success(res) {
						console.log('断开蓝牙连接', res)
					}
				});
				await sleep(500)
				//关闭蓝牙模块
				uni.closeBluetoothAdapter({
					success(res) {
						console.log('关闭蓝牙模块', res)
					}
				})
			},
			async onCancel() {
				// uni.showLoading({
				//   title: 'loading'
				// })
				try {
					const res = await UpdateReagentResult({
						DeviceNo: this.deviceNumber,
						Phone: this.$store.state.vx_u_info.Phone,
						IsNeedContact: false
					})
					if (res.Code === 200) {
						console.log('UpdateReagentResult => ', res)
						this.customLog('UpdateReagentResult => ', res)
					}
				} finally {
					this.$refs.popup.close()
					// uni.hideLoading()
				}
			},
			async onNeed() {
				// this.isBack = true
				// this.close()
				// this.$refs.popup.close()
				// uni.redirectTo({ url: '/pages/hospital/index'})
				uni.showLoading({
					title: 'loading'
				})
				try {
					const res = await UpdateReagentResult({
						DeviceNo: this.deviceNumber,
						Phone: this.$store.state.vx_u_info.Phone,
						IsNeedContact: true
					})
					if (res.Code === 200) {
						console.log('UpdateReagentResult => ', res)
						this.customLog('UpdateReagentResult => ', res)
					}
				} catch (e) {
					this.customLog('需要调用方法 UpdateReagentResult 错误', e)
					console.log(e)
				} finally {
					uni.hideLoading()
					this.isBack = true
					this.close()
					this.$refs.popup.close()
					uni.navigateTo({
						url: '/pages/hospital/index'
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		width: 100vw;
		height: 100vh;
		background-color: #1658CE;
		position: relative;
		display: flex;
		flex-direction: column;

		.log {
			width: 50rpx;
			height: 50rpx;
			position: absolute;
			right: 50rpx;
			bottom: 50rpx;
			z-index: 10;
		}

		.logs {
			position: relative;
			width: 100vw;
			height: 100vh;
			background: #ffffff;
			margin: 80rpx;
			overflow: scroll;
			z-index: 1000;

			.log-close {
				width: 100rpx;
				height: 50rpx;
				position: fixed;
				right: 80rpx;
				top: 200rpx;
				font-size: 20rpx;
			}

			.log-item {
				border-bottom: 1px solid #E5E5E5;
				color: #1B1C1E;
				font-size: 20rpx;
			}

		}

		.nav-style {
			position: fixed;
			top: 0;
			right: 0;
			left: 0;
			z-index: 1000;
			display: flex;
			padding-left: 23rpx;
			align-items: center;
			justify-content: center;

			.small-logo {
				width: 100rpx;
				height: 35rpx;
			}

			.back-img {
				width: 36rpx;
				height: 36rpx;
				position: absolute;
				left: 23rpx;
				bottom: 0;
				margin: auto;
			}
		}

		.process-wrap {
			padding-bottom: 50rpx;
			box-sizing: border-box;
		}

		.wrap {
			flex: 1;
			width: 100%;
			height: 100%;
			margin-top: 36rpx;
			overflow: scroll;
		}

		.popup-wrap {
			width: 615.38rpx;
			height: 617.31rpx;
			padding: 42rpx;
			box-sizing: border-box;
			position: relative;
			border-radius: 30rpx;

			.popup-bg {
				width: 615.38rpx;
				height: 617.31rpx;
				position: absolute;
				top: 0;
				left: 0;
				z-index: 0;
			}

			.popup-container {
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0;
				left: 0;
			}

			.popup-title {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				text-align: center;
				margin-top: 34rpx;

				.popup-img {
					width: 130rpx;
					height: 150rpx;
				}

				.popup-text {
					margin-top: 60rpx;
					margin-left: 22rpx;
					font-size: 32rpx;
					font-weight: bold;
					color: #000000;
				}
			}

			.popup-content {
				width: 515rpx;
				margin: 35rpx auto;
				font-size: 27rpx;
				font-weight: 400;
				color: #333333;
				line-height: 40rpx;
				text-align: center;
			}

			.popup-btn-wrap {
				width: 515.38rpx;
				position: absolute;
				left: 0;
				right: 0;
				bottom: 42rpx;
				margin: auto;
				display: flex;
				justify-content: space-between;
			}

			.popup-btn {
				width: 250rpx;
				height: 85rpx;
				line-height: 85rpx;
				font-size: 28rpx;
				font-weight: 400;
				text-align: center;
				border-radius: 15rpx;

				&.cancel {
					color: #333333;
					background: #EBEBED;

				}

				&.need {
					background: #1E64E1;
					color: #ffffff;
				}
			}
		}
	}
</style>